package com.intelligentclass.services;

import com.intelligentclass.entity.Commit;
import com.intelligentclass.entity.Homework;
import com.intelligentclass.repositories.CommitRepository;
import com.intelligentclass.repositories.HomeworkRespository;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.List;

@Service
public class CommitService {

    private final String base_url = "D:/IntelligentClass/homeworks";
    private final CommitRepository commitRepository;
    private final HomeworkRespository homeworkRespository;
    public CommitService(CommitRepository commitRepository, HomeworkRespository homeworkRespository) {
        this.commitRepository = commitRepository;
        this.homeworkRespository = homeworkRespository;
    }

    public String commitHomework(String sno, int hid, int cid, MultipartFile file) {
        if(file.isEmpty()){
            return "FILE IS EMPTY";
        }
        try {
            Commit commit = commitRepository.findByHidAndSno(hid, sno);
            if(commit == null){
                commit = new Commit();
                commit.setSno(sno);
                commit.setHid(hid);
            }
            String fileName = file.getOriginalFilename();

            String hname = homeworkRespository.findHnameByHid(hid);

            String path = base_url + File.separator + cid + File.separator + sno + File.separator + hname;
            File folder = new File(path);
            if(!folder.exists()){
                folder.mkdirs();
            }
            Path filePath = new File(path, fileName).toPath();
            System.out.println(filePath.toString());
            commit.setDir(filePath.toString());
            commitRepository.save(commit);

            Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);

            return filePath.toString();

        }catch(IOException e) {
            return "WRONG";
        }
    }

    public List<Commit> findAll(int hid) {
        return commitRepository.findCommits(hid);
    }

    public Commit getCommit(int commitid){
        return commitRepository.findById(commitid).orElse(null);
    }
}
